package com.woniuxy.portal.controller;

import com.woniuxy.common.RedisConst;
import com.woniuxy.portal.common.enumeration.Assert;
import com.woniuxy.portal.common.enumeration.BusinessCode;
import com.woniuxy.portal.model.vo.CartVo;
import com.woniuxy.portal.service.CartService;
import com.woniuxy.portal.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author yellow Docter
 * @date 2024-10-25
 * @desc 蜗牛创想：www.woniuxy.com
 */
@RestController
@RequestMapping("/cart")
@Api(tags = "购物车接口")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping
    @ApiOperation("查询购物车")
    public ResponseEntity<CartVo> getCart(@RequestHeader(name = "Authorization", required = false) String token) {
        log.info("获取的token:{}",token);
        //01 校验token 是否过期
//        Assert.error(!jwtUtil.validateToken(token), BusinessCode.INVALID_TOKEN);
        //02 解析token 拿到userId
        String  userId = jwtUtil.getValue(token,"userId");
        //03 调用个业务方法
        CartVo cartVo = cartService.getCart(Long.valueOf(userId));
        log.info("查询购物车成功，购物车信息为：{}", cartVo);
        return ResponseEntity.ok(cartVo);
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("/{bookId}")
    @ApiOperation("添加商品到购物车")
    public ResponseEntity<CartVo> addCartItem(
            @RequestHeader(name = "Authorization", required = false) String token,
            @PathVariable("bookId") Long bookId) {
        //01 校验token 是否过期
//        Assert.error(!jwtUtil.validateToken(token), BusinessCode.INVALID_TOKEN);
        //02 拿到userId
        String  userId = jwtUtil.getValue(token,"userId");
        //03 调用业务方法
        CartVo cartVo = cartService.addCartItem(Long.valueOf(userId), bookId);

        return ResponseEntity.ok(cartVo);
    }

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取我的购物车
     */
    @GetMapping("/myCartDetails")
    @ApiOperation("获取我的购物车")
    public ResponseEntity<CartVo> myCartDetails(@RequestHeader(name = "Authorization", required = false) String token) {
        //获取用户ID
        String userId = jwtUtil.getValue(token, "userId");
        //从Redis中获取购物车的数据
        CartVo cart = (CartVo) redisTemplate.opsForValue().get(RedisConst.USER_CART_PREFIX + ":" + userId);
        return ResponseEntity.ok(cart);
    }
}
